package com.sinodata.bsm.cicp.finder.linux;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.util.CommandReader;

/**
 * <p>Title: Net</p>
 * <p>Description: LINUX平台,网络自我发现程序</p>
 * <p>Copyright: Copyright (c) 2004</p>
 * @author zhaoch
 * @version 1.0
 */

public class LinuxNetstat extends LinuxFinder {

    private static final Logger logger = Logger.getLogger(LinuxNetstat.class);

    private static final String CMDSTR = " netstat -i";

    @SuppressWarnings("unchecked")
    @Override
    public List<String[]> find(String ip, Map params) {
        String[] niInfo = null;
        List<String[]> list = new ArrayList<String[]>();
        String strLine = null;
        BufferedReader reader = null;
        try {
            reader = CommandReader.getReader(ip, CMDSTR, 0, 0);
            while ((strLine = reader.readLine()) != null) {
                StringTokenizer st = new StringTokenizer(strLine);
                if (st.countTokens() == 12) {
                    String name = st.nextToken().trim();
                    if (!name.equals("Iface") && !name.endsWith("*")) {
                        niInfo = new String[4];
                        list.add(niInfo);
                        niInfo[0] = name;
                        niInfo[1] = name;
                        niInfo[2] = getHostName(ip) + " Network Interface " + name;
                        niInfo[3] = name; //物理接口名
                    }
                }
            }
            return list;
        } catch (Exception e) {
            logger.error("failed to find Network Interface Automatically:", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("failed to close reader", e);
                }
            }
        }
        return null;
    }
}
